package ducky.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ducky.models.DatabaseManager;

/**
 * Servlet implementation class Authentication
 */
public class Authentication extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Authentication() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PrintWriter writer = response.getWriter();
		if(username.equals("ducky") && password.equals("funnyguy")){
			writer.println("Hello World "+username+" <br>");
			writer.println("Username "+ username + " has "+ password);
		}
		else{
			writer.println("username or password is incorrect");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		PrintWriter writer = response.getWriter();
		DatabaseManager dm = new DatabaseManager();
		if(dm.checkUser(username, password)){
			for(Cookie c: request.getCookies()){
				System.out.println(c.getName());
				System.out.println(c.getValue());
			}
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			RequestDispatcher dispatche = request.getRequestDispatcher("/ImageShow");
			request.setAttribute("imageName", "Good look");
			dispatche.forward(request, response);
		}
		else{
			response.sendRedirect("index.jsp");
		}
		
		
	}

}
